import React, { memo, useRef, FC } from 'react';
import { FormInstance } from 'antd/lib/form';
// import styles from './index.less';
import CommonModal from '@/components/CommonModal';
import AddForm from './AddForm';
import UserForm from './UserForm';
import { modelName } from '../../../../index';
import useHoxModel from '../../../../useHoxModel';
import { ActionType } from '@/components/ProTable';
import { ConfigPermissionParamsType } from '../../../../API';
import { Row, Col } from 'antd';
import PermissionsDetail from './PermissionsDetail';

interface Props {
  actionRef: React.MutableRefObject<ActionType | undefined>;
}
export const PermissionsConfig = ({
  currentPageType,
  info,
  actionRef,
  modelName,
}: {
  currentPageType: string;
  info: { id?: number };
  actionRef: React.MutableRefObject<ActionType | undefined>;
  modelName: string;
}) => {
  const formRef = useRef<FormInstance>();
  const userFormRef = useRef<FormInstance>();
  const { configPermission } = useHoxModel(() => []);
  return (
    <CommonModal
      title="权限配置"
      width={600}
      type={modelName + 'permissionsConfig'}
      onOk={async (cancelModal: (type?: string, clear?: boolean) => void) => {
        const filterData = async (fields: any) => {
          return {
            userIds:
              currentPageType === 'user'
                ? (info?.id && info?.id.toString()) || ''
                : fields.selectedUser.list
                    .map((item: { id: number }) => {
                      return item.id;
                    })
                    .join(','),

            doorIds:
              currentPageType === 'door'
                ? (info?.id && info?.id.toString()) || ''
                : fields.selectedDoor.list
                    .map((item: { id: number }) => {
                      return item.id;
                    })
                    .join(','),
          };
        };
        await confim<ConfigPermissionParamsType>({
          cancel: cancelModal,
          request: configPermission,
          filterData,
          actionRef,
          userFormRef,
          formRef,
        });
      }}
    >
      {currentPageType === 'user' ? (
        <AddForm formRef={formRef} info={info} />
      ) : (
        <UserForm userFormRef={userFormRef} info={info} />
      )}
    </CommonModal>
  );
};
const confim = async <T extends {}>({
  cancel,
  request,
  filterData,
  formRef,
  userFormRef,
  actionRef,
}: {
  cancel: () => void;
  request: (params: T) => Promise<any>;
  filterData?: (props: any) => Promise<any>;
  formRef?: React.MutableRefObject<FormInstance | undefined>;
  userFormRef?: React.MutableRefObject<FormInstance | undefined>;
  actionRef: React.MutableRefObject<ActionType | undefined>;
}) => {
  try {
    const doorFields: any = await (formRef && formRef.current?.validateFields
      ? formRef.current?.validateFields()
      : {});
    const userFields: any = await (userFormRef &&
      (userFormRef.current?.validateFields ? userFormRef.current?.validateFields() : {}));
    const fields = { ...doorFields, ...userFields };
    const params = await (filterData ? filterData(fields) : fields);

    let res = await request(params);

    if (res.result === 0) {
      actionRef.current?.reloadAndRest();
      cancel();
    }
  } catch (errorInfo) {
    console.log('Failed:', errorInfo);
  }
};

const ModalContent: FC<Props> = (props) => {
  const { actionRef } = props;
  const { configPermission, currentPageType, info } = useHoxModel((model) => [
    model.doorInfo,
    model.info,
  ]);
  const formRef = useRef<FormInstance>();
  const userFormRef = useRef<FormInstance>();

  return (
    <>
      <CommonModal footer={false} title="权限详情" width={800} type={modelName + 'detail'}>
        <PermissionsDetail currentPageType={currentPageType} info={info} />
      </CommonModal>
      <PermissionsConfig
        currentPageType={currentPageType}
        info={info}
        modelName={modelName}
        actionRef={actionRef}
      />
      <CommonModal
        title="全局权限配置"
        width={900}
        type={modelName + 'add'}
        onOk={async (cancelModal: (type?: string, clear?: boolean) => void) => {
          const filterData = async (fields: any) => {
            return {
              userIds: fields.selectedUser.list
                .map((item: { id: number }) => {
                  return item.id;
                })
                .join(','),
              doorIds: fields.selectedDoor.list
                .map((item: { id: number }) => {
                  return item.id;
                })
                .join(','),
            };
          };
          await confim<ConfigPermissionParamsType>({
            cancel: cancelModal,
            request: configPermission,
            filterData,
            formRef,
            userFormRef,
            actionRef,
          });
        }}
      >
        <Row>
          <Col span={12}>
            <AddForm formRef={formRef} info={info} userFormRef={userFormRef} />
          </Col>
          <Col span={12}>
            <UserForm userFormRef={userFormRef} info={info} formRef={formRef} />
          </Col>
        </Row>
      </CommonModal>
    </>
  );
};

export default memo(ModalContent);
